import Vue from "vue";
import Vuex from "vuex";
import globalApi from "@/api/index.js";
import { addRouter } from "@/router";
import { loopMenuFilterIsShow, loopMenuForFlatten, getMenuFilterCode, getMenuFilterPermission } from "@/router/routerUtils";
import { cloneDeep } from "lodash";

Vue.use(Vuex);
export default new Vuex.Store({
  state: {
    menuList: [],
    userInfo: {},
    roleList: [],
    keepAlive: [],
    permission: []
  },
  getters: {},
  mutations: {
    setMenuList(state, menuList) {
      state.menuList = menuList;
    },
    setRoleList(state, roleList) {
      state.roleList = roleList;
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo;
    },
    setKeepAlive(state, keepAlive) {
      state.keepAlive = keepAlive;
    },
    setPermission(state, permission) {
      state.permission = permission;
    },
    logout(state) {
      state.menuList = [];
      state.userInfo = {};
      state.roleList = [];
      state.keepAlive = [];
      state.permission = [];
    },
  },
  actions: {
    async getUserInfo({ commit }) {
      try {
        const res = await globalApi.login.getUserInfoApi();
        commit("setUserInfo", res);
        commit("setMenuList", loopMenuFilterIsShow(cloneDeep(res.menuList)));
        commit("setRoleList", res.belongRole);
        const flattenMenu = loopMenuForFlatten(cloneDeep(res.menuList));
        commit("setKeepAlive", getMenuFilterCode(flattenMenu));
        commit("setPermission", getMenuFilterPermission(flattenMenu));
        addRouter(res.menuList);
      } catch (err) {
        console.log("获取当前登陆人报错了", err);
      }
    },
  },
  modules: {},
});
